//
//  LFAddClockTool.m
//  AlarmClock
//
//  Created by LF on 2017/4/26.
//  Copyright © 2017年 LF. All rights reserved.
//

#import "LFAddClockTool.h"
#import <UserNotifications/UserNotifications.h>

@interface LFDate : NSObject

@property (nonatomic, assign) NSInteger year; /**< 年 */
@property (nonatomic, assign) NSInteger month; /**< 月 */
@property (nonatomic, assign) NSInteger day; /**< 日 */
@property (nonatomic, assign) NSInteger hour; /**< 时 */
@property (nonatomic, assign) NSInteger minute; /**< 分 */

-(instancetype)initWithFireDate:(NSDate *) date;
@end

@implementation LFDate

- (instancetype)initWithFireDate:(NSDate *)date
{
    self = [super init];
    if (!self) {
        return nil;
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd-hh-mm"];
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    NSArray *allTimes = [dateString componentsSeparatedByString:@"-"];
    
    self.year = [allTimes[0] integerValue];
    self.month = [allTimes[1] integerValue];
    self.day = [allTimes[2] integerValue];
    self.hour = [allTimes[3] integerValue];
    self.minute = [allTimes[4] integerValue];
    
    return self;
}

@end

@implementation LFAddClockTool

+ (void)registerNotification:(LFAlarmClockModel *)notiInfo
{
    if ([UIDevice currentDevice].systemVersion.intValue >= 10.0) {
        [self iOS10Noti:notiInfo];
    } else {
        [self lessThaniOS10Noti:notiInfo];
    }
}

#pragma mark - 使用 UNNotification 本地通知
+ (void)iOS10Noti:(LFAlarmClockModel *)notiInfo {
    
    NSInteger alertTime = 4;
    NSString *dateString = [notiInfo.date stringByAppendingString:[NSString stringWithFormat:@"-%@",notiInfo.time]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd-hh-mm"];
    // 设置触发通知的时间
    NSDate *fireDate = [dateFormatter dateFromString:dateString];
    
    LFDate *lfDate = [[LFDate alloc] initWithFireDate:fireDate];
    
    NSString *categoryIdentifier = [NSString stringWithFormat:@"iOS10Noti_Cate%zd",[[NSDate date] timeIntervalSince1970]];
    
    // 使用 UNUserNotificationCenter 来管理通知
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    
    //需创建一个包含待通知内容的 UNMutableNotificationContent 对象，注意不是 UNNotificationContent ,此对象为不可变对象。
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.badge = @1;
    content.title = [NSString localizedUserNotificationStringForKey:notiInfo.message_title arguments:nil];
    content.subtitle = [NSString localizedUserNotificationStringForKey:notiInfo.message_subTitle arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:notiInfo.message_body arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    content.categoryIdentifier = categoryIdentifier;
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:notiInfo.identifier forKey:@"identifier"];
    content.userInfo = userDict;
    NSString *path = [[NSBundle mainBundle] pathForResource:notiInfo.image ofType:@"jpg"];
    if (path) {
        NSURL *url = [NSURL fileURLWithPath:path];
        UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"objc" URL:url options:nil error:nil];
        content.attachments = @[attachment];
    }
    
    //带评论的通知事件注册
    UNTextInputNotificationAction *inputAction = [UNTextInputNotificationAction actionWithIdentifier:@"input" title:@"评论" options:UNNotificationActionOptionForeground textInputButtonTitle:@"发送" textInputPlaceholder:@"请输入评论内容.."];
    UNNotificationAction *openAction = [UNNotificationAction actionWithIdentifier:@"open" title:@"打开" options:UNNotificationActionOptionForeground];
    UNNotificationAction *cancleAction = [UNNotificationAction actionWithIdentifier:@"cancle" title:@"取消" options:UNNotificationActionOptionDestructive];
    
    UNNotificationCategory *tapCategory = [UNNotificationCategory categoryWithIdentifier:@"comment" actions:@[inputAction,openAction,cancleAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
    
    //自定义UI通知的时间注册
    UNNotificationAction *nextAction = [UNNotificationAction actionWithIdentifier:@"switch" title:@"切换" options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationCategory *customCategory = [UNNotificationCategory categoryWithIdentifier:categoryIdentifier actions:@[nextAction,openAction,cancleAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionNone];
    
    //
    NSSet *set = [[NSSet alloc]initWithObjects:tapCategory, customCategory, nil];
    [center setNotificationCategories:set];
    
    
    
    // 在 alertTime 后推送本地推送
    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:alertTime repeats:NO];
    
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.hour = lfDate.hour;
    dateComponents.minute = lfDate.minute;
    UNCalendarNotificationTrigger *trigger2 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
    
    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                          content:content trigger:trigger2];
    
    //添加推送成功后的处理！
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:@"成功添加推送" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:cancelAction];
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
            
            [self storeAlarmInfo:notiInfo];
        }
    }];
}

#pragma mark - 使用 UILocalNotification 本地通知
+ (void)lessThaniOS10Noti:(LFAlarmClockModel *)notiInfo {
    
    NSString *categoryIdentifier = [NSString stringWithFormat:@"lessThaniOS10Noti_Cate%zd",[[NSDate date] timeIntervalSince1970]];
    NSString *dateString = [notiInfo.date stringByAppendingString:[NSString stringWithFormat:@"-%@",notiInfo.time]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd-hh-mm"];
    
    // 创建通知
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSDate *fireDate = [dateFormatter dateFromString:dateString];
    
    // 时间
    notification.fireDate = fireDate;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    
    // 通知内容
    notification.alertTitle = notiInfo.message_title;
    notification.alertBody = notiInfo.message_body;
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:notiInfo.identifier forKey:@"identifier"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        
        UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init];
        action.title = @"打开";
        action.identifier = @"open";
        action.activationMode = UIUserNotificationActivationModeForeground;
        UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init];
        category.identifier = categoryIdentifier;
        [category setActions:@[action] forContext:UIUserNotificationActionContextDefault];
        
        UIUserNotificationType type = UIUserNotificationTypeAlert |
                                      UIUserNotificationTypeBadge |
                                      UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:[NSSet setWithObjects:category, nil]];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    }
    
    notification.category = categoryIdentifier;
    
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    
    [self storeAlarmInfo:notiInfo];
}

+ (void) storeAlarmInfo:(LFAlarmClockModel *)alarmInfo {
    
    LFDBHelper *dbHelper = [LFDBHelper helper];
    
    // 检测是否已经存在了
    [dbHelper itemExistsForAlarmClock:alarmInfo withResultBlock:^(BOOL isiExist) {
        if (isiExist) {
            // 存在就刷新
            [dbHelper updateAlarmClock:alarmInfo];
            NSLog(@"已经有了, 刷新一下");
        }
        else {
            // 不存在就插入
            [dbHelper insertAlarmClock:alarmInfo];
            NSLog(@"新的一个,插入一条");
        }
    }];
}


@end
